from fastapi import APIRouter, Depends, HTTPException, status, Query
from typing import List, Optional, Dict

from app.dependencies_json import get_current_user, get_task_service
from app.models.schemas import (
    APIResponse, TaskInfo, TaskCreateRequest, TaskUpdateRequest, 
    TaskListParams, PaginatedResponse, TaskStatus
)
from app.services.json_task_service import JSONTaskService

router = APIRouter(tags=["tasks"])

@router.post("/", response_model=APIResponse[TaskInfo])
def create_task(
    request: TaskCreateRequest,
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """创建新任务"""
    try:
        # 创建任务
        task_info = task_service.create_task(config=request.config)
        
        # 如果需要立即执行，启动任务
        if request.execute_immediately:
            task_service.start_task(task_info.id)
        
        return APIResponse(
            message="任务创建成功",
            data=task_info
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建任务失败: {str(e)}"
        )

@router.get("/", response_model=APIResponse[PaginatedResponse])
def list_tasks(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    status_filter: Optional[TaskStatus] = Query(None, alias="status", description="状态过滤"),
    search: Optional[str] = Query(None, description="关键词搜索"),
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """获取任务列表"""
    try:
        params = TaskListParams(
            page=page,
            size=size,
            status=status_filter,
            search=search
        )
        
        result = task_service.list_tasks(params=params)
        
        return APIResponse(
            message="获取任务列表成功",
            data=result
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取任务列表失败: {str(e)}"
        )

@router.get("/{task_id}", response_model=APIResponse[TaskInfo])
def get_task(
    task_id: str,
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """获取任务详情"""
    try:
        task_info = task_service.get_task(task_id)
        if not task_info:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在"
            )
        
        return APIResponse(
            message="获取任务详情成功",
            data=task_info
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取任务详情失败: {str(e)}"
        )

@router.put("/{task_id}", response_model=APIResponse[TaskInfo])
def update_task(
    task_id: str,
    request: TaskUpdateRequest,
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """更新任务"""
    try:
        task_info = task_service.update_task(task_id, request.config)
        if not task_info:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在"
            )
        
        return APIResponse(
            message="任务更新成功",
            data=task_info
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新任务失败: {str(e)}"
        )

@router.delete("/{task_id}", response_model=APIResponse[bool])
def delete_task(
    task_id: str,
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """删除任务"""
    try:
        success = task_service.delete_task(task_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在"
            )
        
        return APIResponse(
            message="任务删除成功",
            data=True
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除任务失败: {str(e)}"
        )

@router.post("/{task_id}/start", response_model=APIResponse[bool])
def start_task(
    task_id: str,
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """启动任务"""
    try:
        success = task_service.start_task(task_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在或无法启动"
            )
        
        return APIResponse(
            message="任务启动成功",
            data=True
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"启动任务失败: {str(e)}"
        )

@router.post("/{task_id}/stop", response_model=APIResponse[bool])
def stop_task(
    task_id: str,
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """停止任务"""
    try:
        success = task_service.stop_task(task_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在或无法停止"
            )
        
        return APIResponse(
            message="任务停止成功",
            data=True
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"停止任务失败: {str(e)}"
        )

@router.get("/{task_id}/status", response_model=APIResponse[Dict])
def get_task_status(
    task_id: str,
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """获取任务状态"""
    try:
        status_info = task_service.get_task_status(task_id)
        if not status_info:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="任务不存在"
            )
        
        return APIResponse(
            message="获取任务状态成功",
            data=status_info
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取任务状态失败: {str(e)}"
        )

@router.get("/{task_id}/logs", response_model=APIResponse[List[Dict]])
def get_task_logs(
    task_id: str,
    limit: int = Query(100, ge=1, le=1000, description="日志数量限制"),
    current_user: dict = Depends(get_current_user),
    task_service: JSONTaskService = Depends(get_task_service)
):
    """获取任务日志"""
    try:
        logs = task_service.get_task_logs(task_id, limit=limit)
        
        return APIResponse(
            message="获取任务日志成功",
            data=logs
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取任务日志失败: {str(e)}"
        )
